﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShareCode.Util.Helper
{
    public static class ObjectHelper
    {
        private static readonly List<string> CopyValuesForRepair_IgnoreField = new() { "Id", "TheAction", "ActionTargetId", "VersionId" };
        public static T CopyValuesForRepair<T>(this T target, T source)
        {
            target.CopyValues(source, CopyValuesForRepair_IgnoreField);
            return target;
        }

        public static T CopyValues<T>(this T target, T source)
        {
            target.CopyValues(source, null);
            return target;
        }

        public static T CopyValues<T>(this T target, T source, List<string>? IgnoreField)
        {
            Type t = typeof(T);
            var properties = t.GetProperties().Where(prop => prop.CanRead && prop.CanWrite);

            foreach (var prop in properties)
            {
                if (IgnoreField != default && IgnoreField.Contains(prop.Name))
                {
                    continue;
                }

                var value = prop.GetValue(source, null);
                if (value != null)
                    prop.SetValue(target, value, null);
            }

            return target;
        }


        public static long ObjToLong(this object thisValue)
        {
            long result = default(long);
            if (thisValue != null && thisValue != DBNull.Value && long.TryParse(thisValue.ToString(), out result))
            {
                return result;
            }

            return 0L;
        }


        public static T GetInsertObject<T>() where T : new()
        {
            T re = new();
            Type strType = typeof(String);

            var Properties = typeof(T).GetProperties().Where(t => t.CanWrite && t.PropertyType == strType);

            foreach (var prop in Properties)
            {
                prop.SetValue(re, "");
            }

            return re;
        }
        public static T GetInsertObject<T>(T obj) where T : new()
        {
            if (obj == null) {
                return obj;
            }

            Type strType = typeof(String);

            var Properties = obj.GetType().GetProperties().Where(t => t.CanWrite && t.PropertyType == strType);

            foreach (var prop in Properties)
            {
                if (prop.GetValue(obj) == default)
                {
                    prop.SetValue(obj, "");
                }
            }

            return obj;
        }
    }
}
